#!/usr/bin/env python
#-*- coding:utf8 -*-
import web
class Model(object):
    db = web.config.get('database')
    def get(self,_map):
        try:
            return self.db.select(self.table, where ="id = %s" % _map, limit = 1, vars = locals())[0]
        except:
            return None

    def get_by(self, _map):
        try:
            return self.db.select(self.table, where = "%s" % _map, limit = 1, vars = locals())[0]
        except:
            return None

    def get_all(self, _order = 'id desc'):
        try:
            return self.db.select(self.table, limit = 30, order = _order, vars = locals())
        except:
            return None

    def get_many_by(self,_map, _limit = 30, _order = 'id desc'):
        try:
            return self.db.select(self.table, where = "%s" % _map, limit = _limit, order = _order, vars = locals())
        except:
            return None

    def insert(self,**kwargs):
        try:
            return self.db.insert(self.table, **kwargs)
        except:
            return False

    def save(self, _map, **kwargs):
        try:
            return self.db.update(self.table,where = "id = %s" % _map, **kwargs)
        except:
            return False

    def save_by(self,_map, **kwargs):
        try:
            return self.db.update(self.table, where = "%s" % _map, **kwargs)
        except:
            return False

    def delete(self,_map):
        try:
            return self.db.delete(self.table, where = "id = %s" % _map)
        except:
            return False

    def delete_by(self,_map):
        try:
            return self.db.delete(self.table, where = "%s" % _map)
        except:
            return False

    def count_by(self, _map):
        try:
            return self.db.query("SELECT COUNT(*) AS total FROM %s where %s" % (self.table,_map))[0].total
        except:
            return None

    def query(self,sql):
        try:
            return self.db.query(sql)
        except:
            return False
